package top.dotgo.web.base;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import top.dotgo.kit.ex.DotException;
import top.dotgo.kit.ex.DotMsg;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : lin
 * @date : 2019/9/27 15:10
 * 统一返回值格式
 */
@Getter
@Setter
@Accessors(chain = true)
@SuppressWarnings("AlibabaClassNamingShouldBeCamel")
public class R {

    private Integer code = DotMsg.SUCCESS_CODE;

    private String msg = DotMsg.SUCCESS_MSG;
    private Object data;


    public static R ok(Object data) {
        return new R().setData(data);
    }


    public static R ok() {
        return new R();
    }

    public static R err(String msg, String... args) {
        return err(DotMsg.ERROR_CODE, msg, args);
    }

    public static R err(int code, String msg, Object... args) {
        if (args != null && args.length > 0 && args[0] != null) {
            return new R().setCode(code).setMsg(StrUtil.format(msg, args));
        } else {
            return new R().setCode(code).setMsg(msg);
        }
    }


    @SuppressWarnings("unchecked")
    public R put(String key, Object value) {
        if (data == null) {
            data = new HashMap<String, Object>(5);
        } else if (!(data instanceof Map)) {
            data = BeanUtil.beanToMap(data);
        }
        ((Map<String, Object>) data).put(key, value);
        return this;
    }

    /**
     * 转对象
     *
     * @param clazz clazz
     * @param <T>   T
     * @return T
     */
    public <T> T getData(Class<T> clazz) {
        if (data instanceof JSONArray) {
            throw new DotException("this data is arr");
        }
        return ((JSONObject) data).toJavaObject(clazz);
    }

    /**
     * 转 list
     *
     * @param clazz clazz
     * @param <T>   T
     * @return List<T>
     */
    public <T> List<T> getDataArr(Class<T> clazz) {
        if (data instanceof JSONObject) {
            throw new DotException("this data is object");
        }
        return ((JSONArray) data).toJavaList(clazz);
    }


    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }
}
